package ctrl

import (
	"net/http"
	"os"
	"../util"
	"strings"
	"fmt"
	"time"
	"math/rand"
	"io"
	"../common"
)

//上传图片
func Upload(w http.ResponseWriter, r *http.Request) {
	UploadLocal(w, r)
}

//1.存储位置 ./mnt,需要确保已经创建好
//2.url格式 /mnt/xxxx.png 需要确保网络能访问/mnt/
func UploadLocal(writer http.ResponseWriter, request *http.Request) {
	//获得上传的源文件
	srcfile, head, err := request.FormFile("file")
	if err != nil {
		util.RespFail(writer, err.Error())
	}

	//创建一个新文件
	suffix := ".png" //后缀
	//如果前端文件名称包含xxxx.png
	ofilename := head.Filename //获取文件名称
	tmp := strings.Split(ofilename, ".")
	if len(tmp) > 1 {
		suffix = "." + tmp[len(tmp)-1]
	}
	//如果前端文件指定filetype
	filetype := request.FormValue("filetype")
	if len(filetype) > 0 {
		suffix = filetype
	}

	//文件名称
	filename := fmt.Sprintf("%d%04d%s", time.Now().Unix(), rand.Int31(), suffix)
	//创建新文件
	dstfile, err := os.Create("./mnt/" + filename)
	if err != nil {
		util.RespFail(writer, err.Error())
		return
	}
	//将源文件内容copy到新文件
	_, err = io.Copy(dstfile, srcfile)
	if err != nil {
		util.RespFail(writer, err.Error())
		return
	}

	//将新文件路径转换成url地址
	url := common.G_config.HttpServerHost+"/mnt/" + filename

	fmt.Println(url)
	util.RespOk(writer, url, "")

}
